<?php

/**
 * This class represents logged user and his attributes.
 * It is designed as an singleton (Design Pattern)
 * @author honza
 */
class Auth {
  static private $instance = NULL;
  static private $identity = NULL;

  private function __construct() {
    session_start();
    if (isset($_SESSION['auth'])) {
      self::$identity = $_SESSION['auth'];
    }
  }

  static function getInstance() {
    if (self::$instance == NULL) {
      self::$instance = new Auth();
    }
    return self::$instance;
  }

  function getIdentity() {
    return self::$identity;
  }

  function hasIdentity() {
    return !self::$identity == NULL;
  }

  public function hasAuthority($ith) {
    if ($this->hasIdentity() && self::$identity['role'] >= $ith) {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  public function hasValidReaderCard() {
    if (self::$identity['platnostPrukazu'] == 'plati') {
      return true;
    } else {
      return false;
    }
  }

  public function login($login, $heslo) {
    $heslo = Auth::encrypt($heslo, $login);
    
    $cols = 'id_user, priority, CURDATE( ) <= library_card_validity as validity';
    $sql = "select " . $cols . " from " . TBL_USERS . ' ' .
            "join " . TBL_ROLES . ' using(id_role) ' .
            "where login='" . $login . "' and pass='" . $heslo . "'";
    $result = DB::sql($sql);

    if ($result) {
      self::$identity = array();
      self::$identity['id'] = $result[0]['id_user'];
      if ($result[0]['validity'] == 1) {
        $validity = 'plati';
      } else {
        $validity = 'neplati';
      }
      self::$identity['platnostPrukazu'] = $validity;
      self::$identity['login'] = $login;
      self::$identity['pass'] = $heslo;
      self::$identity['auth'] = TRUE;
      self::$identity['role'] = $result[0]['priority'];
      return TRUE;
    } else {
      return FALSE;
    }
  }

  public function logout() {
    session_destroy();
    $_SESSION = array();
    self::$identity = array();
    }

    /**
     * 
     * @param type $pass
     * @param type $usr
     * @return string hash of pass and login information
     */
    public static function encrypt($pass, $usr) {
    $password = str_split($pass, (strlen($pass) / 2) + 1);
    $hash = hash('sha256', $usr . $password[0] . HASH_JUNK . $password[1]);
    return $hash;
  }

  function __destruct() {
    $_SESSION['auth'] = self::$identity;
  }

}

?>
